package com.enation.app.javashop.seller.api.aftersale;

import com.enation.app.javashop.core.aftersale.AftersaleErrorCode;
import com.enation.app.javashop.core.aftersale.model.dto.RefundDTO;
import com.enation.app.javashop.core.aftersale.model.dto.RefundDetailDTO;
import com.enation.app.javashop.core.aftersale.model.dto.SpreadRefundDTO;
import com.enation.app.javashop.core.aftersale.model.enums.RefundStatusEnum;
import com.enation.app.javashop.core.aftersale.model.vo.*;
import com.enation.app.javashop.core.aftersale.service.AfterSaleManager;
import com.enation.app.javashop.core.excel.ExcelManager;
import com.enation.app.javashop.core.goods.model.enums.Permission;
import com.enation.app.javashop.core.trade.order.model.dto.RefundOrderDTO;
import com.enation.app.javashop.framework.context.UserContext;
import com.enation.app.javashop.framework.database.Page;
import com.enation.app.javashop.framework.exception.ServiceException;
import com.enation.app.javashop.framework.redis.transactional.RedisTransactional;
import com.enation.app.javashop.framework.security.model.Seller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 * @author zjp
 * @version v7.0
 * @Description 售后相关API
 * @ClassName AfterSaleSellerController
 * @since v7.0 上午9:38 2018/5/10
 */
@Api(description = "售后相关API")
@RestController
@RequestMapping("/seller/after-sales")
@Validated
public class AfterSaleSellerController {

    @Autowired
    private AfterSaleManager afterSaleManager;

    @Autowired
    private ExcelManager excelManager;

    /**
     * 卖家审核退款/退货
     * @param refundApproval 审核退(款)货VO
     * @param sn 退款单号
     * @return 审核退(款)货VO
     */
    @ApiOperation(value = "卖家审核退款/退货", response = RefundApprovalVO.class)
    @PostMapping(value = "/audits/{sn}")
    @ApiImplicitParam(name = "sn", value = "退款单sn", required = true, dataType = "String", paramType = "path")
    @RedisTransactional(acquireTimeout = 1,lockTimeout = 30,lockName = "refund_approval_",value = "#sn")
    public RefundApprovalVO audit(@Valid RefundApprovalVO refundApproval, @PathVariable("sn") String sn) {
        refundApproval.setSn(sn);
        afterSaleManager.approval(refundApproval, Permission.SELLER);
        return refundApproval;
    }

    @ApiOperation(value = "卖家入库操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "退款单编号", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "remark", value = "入库备注", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "is_success", value = "是否入库成功", required = false, dataType = "Boolean", paramType = "query")
    })
    @PostMapping(value = "/stock-ins/{sn}")
    @RedisTransactional(acquireTimeout = 1,lockTimeout = 30,lockName = "stock_in_",value = "#sn")
    public String stockIn(@PathVariable("sn") String sn, String remark,Boolean isSuccess) {
        if (!isSuccess) {
            // 入库失败,自动审核失败
            RefundApprovalVO refundApprovalVO = new RefundApprovalVO();
            refundApprovalVO.setSn(sn);
            refundApprovalVO.setAgree(0);
            refundApprovalVO.setRefundPrice(0.0);
            refundApprovalVO.setRemark("入库失败,系统自动拒绝审核;");
            afterSaleManager.approval(refundApprovalVO, Permission.ADMIN);
        }else {
            // 入库成功
            afterSaleManager.sellerStockIn(sn, remark, Permission.SELLER);
        }
        return "";
    }

    @ApiOperation(value = "卖家退款", response = FinanceRefundApprovalVO.class)
    @PostMapping(value = "/refunds/{sn}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sn", value = "退款(货)编号", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "remark", value = "退款备注", required = false, dataType = "String", paramType = "query")
    })
    public String sellerRefund(@PathVariable("sn") String sn, String remark) {
        this.afterSaleManager.sellerRefund(sn, remark);
        return "";
    }

    @ApiOperation(value = "卖家查看退款(货)详细", response = RefundDetailDTO.class)
    @ApiImplicitParam(name = "sn", value = "退款(货)编号", required = true, dataType = "String", paramType = "path")
    @GetMapping(value = "/refunds/{sn}")
    public RefundDetailDTO sellerDetail(@PathVariable("sn") String sn) {
        Seller seller = UserContext.getSeller();
        RefundDetailDTO detail = this.afterSaleManager.getDetail(sn);
        if (!detail.getRefund().getSellerId().equals(seller.getSellerId())) {
            throw new ServiceException(AftersaleErrorCode.E603.name(), "退款单不存在");
        }
        return detail;
    }

    @ApiOperation(value = "卖家查看退款(货)详细---BY 订单号", response = RefundDetailDTO.class)
    @ApiImplicitParam(name = "order_sn", value = "订单编号", required = true, dataType = "String", paramType = "query")
    @GetMapping(value = "/refunds/queryByOrderSn")
    public RefundDetailDTO sellerDetailByOrderSn(@RequestParam("order_sn") String orderSn) {
        Seller seller = UserContext.getSeller();
        RefundDetailDTO detail = this.afterSaleManager.getDetailByOrderSn(orderSn);
        if (!detail.getRefund().getSellerId().equals(seller.getSellerId())) {
                throw new ServiceException(AftersaleErrorCode.E603.name(), "退款单不存在");
        }
        return detail;
    }

    @ApiOperation(value = "卖家查看退款(货)列表", response = RefundDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "分页数", required = true, dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/refunds")
    public Page sellerDetail(RefundQueryParamVO queryParam, @ApiIgnore @NotNull(message = "页码不能为空") Integer pageNo, @ApiIgnore @NotNull(message = "每页数量不能为空") Integer pageSize) {

        Seller seller = UserContext.getSeller();
        queryParam.setPageNo(Integer.valueOf(pageNo));
        queryParam.setPageSize(pageSize);
        queryParam.setSellerId(seller.getSellerId());
        return this.afterSaleManager.query(queryParam);
    }


    /**
     * JFENG
     * @param pageNo
     * @param pageSize
     * @return
     */
    @ApiOperation(value = "卖家查看待退款(货) 订单列表", response = RefundDTO.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page_no", value = "页码", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "page_size", value = "分页数", required = true, dataType = "int", paramType = "query")
    })
    @GetMapping(value = "/refundOrders")
    public Page refundOrderList(@ApiIgnore @NotNull(message = "页码不能为空") Integer pageNo, @ApiIgnore @NotNull(message = "每页数量不能为空") Integer pageSize) {

        Seller seller = UserContext.getSeller();
        RefundQueryParamVO queryParam = new RefundQueryParamVO();
        queryParam.setPageNo(Integer.valueOf(pageNo));
        queryParam.setPageSize(pageSize);
        queryParam.setSellerId(seller.getSellerId());
        Page<RefundOrderDTO> refundPage = this.afterSaleManager.queryRefundOrders(queryParam);
        return refundPage;

    }

    @ApiOperation(value = "卖家主动取消订单-付款之后", response = FinanceRefundApprovalVO.class)
    @PostMapping(value = "/sellerRefund/{order_sn}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "order_sn", value = "订单编号", required = true, dataType = "String", paramType = "path"),
            @ApiImplicitParam(name = "cancel_reason", value = "退款原因", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "remark", value = "退款备注", required = false, dataType = "String", paramType = "query")
    })
    public String sellerRefund(@PathVariable("order_sn") String orderSn, String remark, String cancelReason) {
        BuyerCancelOrderVO cancelOrderVO=new BuyerCancelOrderVO();
        cancelOrderVO.setOrderSn(orderSn);
        cancelOrderVO.setRefundReason(cancelReason);
        cancelOrderVO.setCustomerRemark(remark);
        this.afterSaleManager.sysCancelOrder(cancelOrderVO);
        return "";
    }


    @ApiOperation(value = "卖家主动给客户退补差价", response = String.class)
    @PostMapping(value = "/refund/spread/{order_sn_list}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "order_sn_list", value = "订单编号数组", allowMultiple = true, required = true, dataType = "String", paramType = "path")
    })
    public List<String> sellerSpreadRefund(@PathVariable("order_sn_list") String[] orderSnList,
                                     @RequestBody @Valid SpreadRefundDTO spreadRefundDTO) {
        Seller seller = UserContext.getSeller();
        return afterSaleManager.spreadRefund(orderSnList, spreadRefundDTO , seller);
    }


    @ApiOperation(value = "卖家分页查询多退少补单", response = SpreadRefundQueryParamVO.class)
    @PostMapping(value = "/refund/spread")
    public Page<SpreadRefundQueryParamVO> querySpreadRefund(@RequestBody SpreadRefundQueryParamVO spreadRefundQueryParamVO) {
        //查询卖家ID
        Seller seller = UserContext.getSeller();
        spreadRefundQueryParamVO.setSellerId(seller.getSellerId());
        return afterSaleManager.querySpreadRefund(spreadRefundQueryParamVO);
    }

    @PostMapping("/refund/spread/export")
    @ApiOperation(value = "退补差价单导出excle", notes = "export", produces = "application/octet-stream")
    public void spreadRefundExport(@RequestBody SpreadRefundQueryParamVO spreadRefundQueryParamVO) {
        spreadRefundQueryParamVO.setSellerId(UserContext.getSeller().getSellerId());
        spreadRefundQueryParamVO.setPageSize(1000);
        excelManager.spreadRefundExport(spreadRefundQueryParamVO);
    }
}
